package com.lagou.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author yangpeng
 * @time 2020/4/21
 * @since 1.0.0
 */
public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> clazz;

    private Serializer serializer;



    public RpcEncoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }



    @Override

    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {
        System.out.println("编码"+msg.toString());
        if (clazz != null && clazz.isInstance(msg)) {

            byte[] bytes = serializer.serialize(msg);

            byteBuf.writeInt(bytes.length);

            byteBuf.writeBytes(bytes);
        }else{
            ByteBuf buf = (ByteBuf) msg;
            byte[] byteFromBuf = getByteFromBuf(buf);
            System.out.println("编码结果："+ new String(byteFromBuf));
            byteBuf.writeInt(byteFromBuf.length);
            byteBuf.writeBytes(byteFromBuf);
        }

    }

    public byte[] getByteFromBuf(ByteBuf buf) {
        int size = buf.readableBytes();
        byte[] bytes = new byte[size];
        buf.readBytes(bytes);
        return bytes;
    }

}
